package com.suos.core.logic;

import com.suos.conf.SuOsProperties;
import com.suos.core.utils.PriUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * @author : MisShi
 * @date: 2021-10-22 15:16:47
 */
public class SugarServer implements Runnable {

    private String inetHost;

    private int inetPort;

    private SuOsProperties suOsProperties;

    public SugarServer() {
    }

    public SugarServer(SuOsProperties suOsProperties) {
        this.suOsProperties = suOsProperties;
        this.inetHost = PriUtil.getHost(suOsProperties.getRegisterUrl());
        this.inetPort = PriUtil.getPort(suOsProperties.getRegisterUrl());
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            //监听
                            ch.pipeline().addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new ObjectDecoder(1024 * 1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())),
                                    new ObjectEncoder());
                            ch.pipeline().addLast(new SugarServerHandler(suOsProperties));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(inetHost, inetPort).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    @SneakyThrows
    @Override
    public void run() {
        this.start();
    }
}
